package chrisbode.cps142.a2;

import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;

public class MovieApp {
	public static void main(String[] args) {
		final String COMMAND_ERROR = "Invalid command. Type 'HELP' or try again.";
		final String HELP = "LISTMOVIES - Lists all movies and their movie ids.\n"
				+ "SELL <MOVIE ID> <ADULT|CHILD> [<AMOUNT>] - Sell a ticket for the specified movie id\n"
				+ "QUIT - Close this program.";
		final NumberFormat dollarFormat = NumberFormat
				.getCurrencyInstance(Locale.US);

		MovieRoster roster;

		try {
			roster = new MovieRoster(new File("movies.txt"));
		} catch (IOException e) {
			System.out.println("There was an error reading the roster file.");
			return;
		}

		double profit = 0;
		boolean cont = true;

		Scanner console = new Scanner(System.in);

		do {
			String cmd = console.nextLine().toUpperCase();

			try {
				if (cmd.startsWith("HELP")) {
					System.out.println(HELP);
				} else if (cmd.startsWith("LISTMOVIES")) {
					roster.listMovies();
				} else if (cmd.startsWith("SELL")) {
					String[] cmdArgs = cmd.split(" ");

					int movie = Integer.parseInt(cmdArgs[1]);
					Patron p = Patron.valueOf(cmdArgs[2]);
					int amount = 1;

					if (cmdArgs.length >= 4) {
						amount = Integer.parseInt(cmdArgs[3]);
					}

					if (p == null) {
						System.out.println(COMMAND_ERROR);
					} else {
						int sold = 0;
						double price = 0;
						boolean sell = true;
						
						while (sell && amount > 0) {
							try {
								price += roster.sell(movie, p);
								sold++;
								amount--;
							} catch (TheatreCapacityException e) {
								System.out.println("Can't sell ticket: the specified show is sold out.");
								sell = false;
							}
						}
						
						profit += price;
						
						System.out.println("Sale of " + sold + " ticket" + (sold!=1?"s":"") + " for " + dollarFormat.format(price));
					}
				} else if (cmd.startsWith("QUIT")) {
					System.out.println("\n\nQUITING:");
					roster.listMovies();
					System.out.println("\n" + dollarFormat.format(profit) + " was made in ticket sales.");
					cont = false;
				}
			} catch (Exception e) {
				System.out.println(COMMAND_ERROR);
			}
		} while (cont);
	}
}
